import { OrbitControls, meshBounds } from '@react-three/drei'
import { useEffect, useRef } from 'react'
import { DirectionalLight, Mesh } from 'three'
import { useFrame, useThree } from '@react-three/fiber'
import { useControls, button } from 'leva'

const Expercise = () => {
  const boxRef = useRef<Mesh>(null!)
  useFrame(({ clock }) => {
    boxRef.current.rotation.y = clock.elapsedTime
  })
  const { position } = useControls({
    position: {
      value: { x: 0, y: 0 },
      step: 0.1,
      max: 5,
      min: -5,
      joystick: 'invertY',
    },
  })
  const { x } = useControls('box', {
    pos: { value: [4, 5] },
    click: button(() => {
      console.log(111)
    }),
    x: { value: 0, max: 4, min: -4, step: 0.01 },
  })
  const { color } = useControls({ color: 'orange' })
  const handleClick = () => {
    console.log('box miss')
  }
  const { scene } = useThree()
  const lightRef = useRef<DirectionalLight>(null!)
  useEffect(() => {
    scene.add(lightRef.current.target)
  }, [scene])
  return (
    <>
      <OrbitControls />
      <directionalLight
        ref={lightRef}
        castShadow
        position={[1, 2, 3]}
        intensity={1.5}
        target-position-x={x}
      />
      <ambientLight color="#fff" intensity={0.5} />
      <mesh castShadow position={[position.x, position.y, 0]}>
        <sphereGeometry />
        <meshStandardMaterial color={color} />
      </mesh>

      <mesh
        castShadow
        position-y={0.5}
        position-x={2}
        ref={boxRef}
        onClick={handleClick}
        raycast={meshBounds}
        onPointerEnter={() => (document.body.style.cursor = 'pointer')}
        onPointerLeave={() => (document.body.style.cursor = 'default')}
      >
        <boxGeometry />
        <meshStandardMaterial color="mediumpurple" />
      </mesh>
      <mesh receiveShadow rotation-x={-Math.PI / 2} scale={10}>
        <planeGeometry />
        <meshStandardMaterial color="greenyellow" />
      </mesh>
    </>
  )
}

export default Expercise
